package com.sxt.practiceapplication.activities;

import androidx.annotation.ColorRes;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.callback.StringCallback;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.sxt.practiceapplication.R;
import com.sxt.practiceapplication.base.BaseActivity;
import com.sxt.practiceapplication.common.ServerStatus;
import com.sxt.practiceapplication.common.Urls;
import com.sxt.practiceapplication.databinding.ActivityRegisterBinding;
import com.sxt.practiceapplication.entity.user.UserRegister;
import com.sxt.practiceapplication.entity.user.data.RegisterResultData;
import com.sxt.practiceapplication.entity.user.data.UsernameCheckResultData;
import com.sxt.practiceapplication.utils.GsonBinder;
import com.sxt.practiceapplication.utils.Tools;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Response;


public class RegisterActivity extends BaseActivity {

    private ActivityRegisterBinding registerBinding;

    private boolean isUsernameAvailable;

    private boolean canDoRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBinding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(registerBinding.getRoot());
        initView();
    }

    private void initView() {
        // 注册按钮点击事件
        registerBinding.buttonRegister.setOnClickListener(v -> {
            String user = getRegisterJson();
            doRegister(user);
        });

        // 账号输入框失去焦点时对输入的账号进行检测
        registerBinding.editAccount.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                checkUsername(((EditText) v).getText().toString());
            }
        });
    }

    private void doRegister(String user) {
        if (user == null) {
            return;
        }
        OkHttpUtils.post(Urls.REGISTER_URL)
                .tag(this)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(user)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {
                        RegisterResultData registerResult = GsonBinder.toObj(result, RegisterResultData.class);
                        if (registerResult != null && registerResult.getCode().equals(ServerStatus.SUCCESS.getCode())) {
                            QMUITipDialog tipDialog = showRegisterResultDialog(true);
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    tipDialog.dismiss();
                                    setResultToLoginOnSuccessful(registerResult.getData());
                                }
                            }, 2000);
                        } else {
                            QMUITipDialog tipDialog = showRegisterResultDialog(false);
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    tipDialog.dismiss();
                                }
                            }, 2000);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        Tools.showErrorDialog(RegisterActivity.this, "服务器错误");
                    }
                });
    }

    private String getRegisterJson() {
        String username = registerBinding.editAccount.getText().toString();
        String nickname = registerBinding.editNickname.getText().toString();
        String password = registerBinding.editPassword.getText().toString();
        int checkedSexId = ((RadioGroup) registerBinding.checkSex).getCheckedRadioButtonId();
        RadioButton sexButton = findViewById(checkedSexId);
        String sex = null;
        if (sexButton != null) {
            sex = sexButton.getText().toString();
        }
        String tel = registerBinding.editTel.getText().toString();
        String email = registerBinding.editEmail.getText().toString();
        UserRegister register = new UserRegister(username, password, tel, sex, email, nickname);
        checkUser(register);
        if (canDoRegister) {
            return GsonBinder.toJsonStr(register);
        }
        return null;
    }

    private void checkUser(UserRegister register) {
        int usernameLen = register.getUsername().length();
        int passwordLen = register.getPassword().length();

        if (!(usernameLen >= 2 && usernameLen <= 20)) {
            showTip(registerBinding.accountTip, "用户名需为2-20个字符", R.color.qmui_config_color_red);
            canDoRegister = false;
        } else {
            if (!isUsernameAvailable) {
                checkUsername(register.getUsername());
                canDoRegister = false;
            } else {
                showTip(registerBinding.accountTip, "用户名可用", R.color.green);
                canDoRegister = true;
            }
        }
        if (!(passwordLen >= 6 && passwordLen <= 20)) {
            showTip(registerBinding.passwordTip, "密码需为6-20个字符", R.color.qmui_config_color_red);
            canDoRegister = false;
        } else {
            registerBinding.editPassword.setTextColor(ContextCompat.getColor(this, R.color.green));
            canDoRegister = true;
        }
    }

    private void checkUsername(String username) {
        if (username != null) {
            OkHttpUtils.get(Urls.USERNAME_CHECK_URL + username)
                    .tag(this)
                    .cacheMode(CacheMode.NO_CACHE)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String result, Call call, Response response) {
                            UsernameCheckResultData checkResultData = GsonBinder.toObj(result, UsernameCheckResultData.class);
                            if (checkResultData != null) {
                                isUsernameAvailable = checkResultData.getData();
                                if (isUsernameAvailable) {
                                    showTip(registerBinding.accountTip, "用户名可用", R.color.green);
                                } else {
                                    showTip(registerBinding.accountTip, "用户已存在", R.color.qmui_config_color_red);
                                }
                            }
                        }
                    });
        }
    }

    private void setResultToLoginOnSuccessful(Map<String, String> data) {
        Intent result = new Intent();
        result.putExtra("username", data.get("username"));
        result.putExtra("password", data.get("password"));
        setResult(LoginActivity.REGISTER_RESULT_CODE, result);
        finish();
    }

    private QMUITipDialog showRegisterResultDialog(boolean isSuccessful) {
        return Tools.showResultTipDialog(
                RegisterActivity.this,
                isSuccessful ? "注册成功" : "注册失败",
                isSuccessful
        );
    }


    @Override
    protected void exitActivity() {
        finish();
    }

    private void showTip(TextView textView, String tip, @ColorRes int colorRes) {
        if (tip != null && tip.length() > 0) {
            textView.setText(tip);
            textView.setVisibility(View.VISIBLE);
            textView.setTextColor(ContextCompat.getColor(this, colorRes));
        }
    }
}